package com.ncs.cns.activity.fragment;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.ncs.cns.R;
import com.ncs.cns.activity.CircuseeDetailActivity;
import com.ncs.cns.business.to.Event;
import com.ncs.cns.business.util.BundleUtil;
import com.ncs.cns.framework.widget.listview.CNSListView;
import com.ncs.cns.framework.widget.listview.CNSListView.IListViewListener;

public class MyCircuSeeFragment extends BaseFragment implements
		IListViewListener, OnItemClickListener {
	private CNSListView mListView;
	private Handler mHandler;
	private MyScrollHandler scrollHandler;
    private MyListAdapter noteBookAdapter;
    private List<Event> eventList;
    private int currentPosition = -1;
	private RefreshTask rtask;
	private LoadMoreTask ltask;

	/** Called when the activity is first created. */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.activity_my_circu_see, null);
		initView(view);
        setData();
        setDataAdapter();
        mListView.startRefresh();
		return view;
	}
	
	@Override
    public void onItemClick(AdapterView<?> listview, View arg1, int position, long arg3) {
		Event event = eventList.get(position-1);
		Intent intent = new Intent(this.getActivity(), CircuseeDetailActivity.class);
		Bundle bundle = BundleUtil.buildEventBundle(event);		
		intent.putExtras(bundle);
		startActivity(intent);
    }
	
	
	   private void initView(View view) {
	       mListView = (CNSListView) view.findViewById(R.id.myCircuseeView);
	       mListView.setRefreshTime(sessionService.getLastRefreshTime(currentUserId));
	       mListView.setOnItemClickListener(this);
	       mListView.setPullLoadEnable(true);
	       mListView.setCNSListViewListener(this);
	       mHandler = new Handler();
	       scrollHandler= new MyScrollHandler();
	       
	    }
	   
	    private void setData() {
	    	eventList = eventService.findByPageForMy(0, mListView.PAGE_LIMIT);
	    }
	
	 
	    private void setDataAdapter(){
	        
	        if (noteBookAdapter == null) {
                noteBookAdapter = new MyListAdapter(getActivity(), eventList);
                mListView.setAdapter(noteBookAdapter);
              
            } else {
                noteBookAdapter.notifyDataSetChanged();
            }
	        
	    }
	    
	private void onLoad() {
	    mListView.stopRefreshOther();
		mListView.stopLoadMore();
		mListView.setRefreshTime(sessionService.getLastRefreshTime(currentUserId));
	}

	public void onRefresh() {
		new RefreshTask().execute();
	}

	public void onLoadMore() {
	   new LoadMoreTask().execute();
	}

	
	class MyListAdapter extends BaseAdapter {
        private Context context;
        private LayoutInflater inflater;
        private List<Event> dataList;

        public MyListAdapter(Activity activity, List<Event> list) {
            this.context = activity;
            this.dataList = list;
            inflater = LayoutInflater.from(context);
        }

        public int getCount() {

            return dataList.size();
        }

        public int getItemViewType(int position) {
            return position;
        }

        public Object getItem(int arg0) {
            return dataList.get(arg0);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.cns_listview_item,
						parent, false);
				holder = new ViewHolder();
				holder.layout_item = (LinearLayout) convertView.findViewById(R.id.layout_item);
				holder.event_title = (TextView) convertView.findViewById(R.id.text_event_title);
				holder.watched_number = (TextView) convertView.findViewById(R.id.text_watched_number);
				holder.event_desc = (TextView) convertView.findViewById(R.id.text_event_desc);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			Event event = dataList.get(position);
			if (event!=null) {
				holder.event_title.setText(event.getEventSubject());
				holder.watched_number.setText(""+event.getEventNumberWatched());
				if(event.getEventStatus().equals("F")){
					holder.event_desc.setText("发送失败");					
				}
				else if(event.getEventStatus().equals("P")){
					holder.event_desc.setText("发送中...");					
				}
				else if(event.getEventStatus().equals("A")){
					holder.event_desc.setText("发送成功");					
				}
			}
			return convertView;
		}

		class ViewHolder {
			public TextView watched_number;
			public LinearLayout layout_item;
			public TextView event_title;
			public TextView event_detail;
			public ImageView iv;
			public TextView event_desc;
		}

		public void notifyDataSetChanged(List<Event> list) {
			dataList = (list);
			super.notifyDataSetChanged();
		}
    }
	
	 @SuppressLint("HandlerLeak")
    class MyScrollHandler extends Handler {///add by hzm start------------------------
	        public MyScrollHandler() {
	            
	        }

	        // 子类必须重写此方法,接受数据
	        @Override
	        public void handleMessage(Message msg) {
	          
	            super.handleMessage(msg);
	            // 此处可以更新UI
	            Bundle b = msg.getData();
	            final int item = b.getInt("item");
	            
	                mListView.startScrollListview(getHeightFromTop(mListView,item));
	        }
	    }
	
	 public int getHeightFromTop(ListView listView,int currentItem){
	     
	     ListAdapter listAdapter = listView.getAdapter();
	     if (listAdapter == null || listAdapter.getCount()==0) 
	     { 
	     // pre-condition 
	          return 0; 
	     } 
	     
	     int totalHeight = 0; 
	     Rect r = new Rect();
	     int firstVisablePose= listView.getFirstVisiblePosition();
	     
	     for (int i = 0; i <= currentItem-firstVisablePose; i++)
	     { 
//    	     View listItem = listAdapter.getView(1+i, null, listView); 
//    	     // listItem.measure(0, 0);  // 0, MeasureSpec.UNSPECIFIED
//    	     listItem.measure( MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST), 
//    	                       MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST)); 
//    	     totalHeight += listItem.getMeasuredHeight(); 
     
	         Boolean flag= listView.getChildAt(i).getGlobalVisibleRect(r);  //必须判断可见与否
             if(flag==true)
    	     totalHeight +=r.height();
	     }
	     
	    // ViewGroup.LayoutParams params = listView.getLayoutParams(); 
	     totalHeight = totalHeight + (listView.getDividerHeight() * (currentItem-firstVisablePose)); 
	   
	     
	     return totalHeight;
	 }//----------------------------------------------------------------------------------------end
	
	 class LoadMoreTask extends AsyncTask<Void, Void, List<Event>> {

			@Override
			protected List<Event> doInBackground(Void... params) {
				List list = eventService.findByPageForMy(mListView.getLastVisiblePosition(), mListView.PAGE_LOAD_SIZE);
				return list;
			}

			@Override
			protected void onPostExecute(List<Event> list) {
				ltask = null;
				noteBookAdapter.notifyDataSetChanged(list);
				mListView.stopLoadMore();
			}
		}

		class RefreshTask extends AsyncTask<Void, Void, Boolean> {
			/* (non-Javadoc)
			 * @see android.os.AsyncTask#doInBackground(Params[])
			 */
			@Override
			protected Boolean doInBackground(Void... arg0) {
				List list = eventService.findByPageForMy(mListView.getLastVisiblePosition(), mListView.PAGE_LOAD_SIZE);
				sessionService.updateLastRefreshTime(currentUserId);
				return list!=null && list.size()>0;
			}

			@Override
			protected void onPostExecute(Boolean success) {
				rtask = null;
				setData();
				noteBookAdapter.notifyDataSetChanged(eventList);
				mListView.setAdapter(noteBookAdapter);
				onLoad();
			}

		}

}